#include "anry-stock-library-config.h"
#include "DataRetrieve.h"

DataRetrieve::DataRetrieve( const char* db_path )
{
	DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_DEBUG, "db_path: %s", db_path );
	
	OpenDatabase( db_path );
}
	
DataRetrieve::~DataRetrieve()
{
	DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_DEBUG, "" );
	
	CloseDatabase();
}

int DataRetrieve::UpdateDatabase()
{
	DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_DEBUG, "" );
	
	return 0;
}

#define CREATE_DATA_RETRIEVE_TABLES "CREATE TABLE IF NOT EXISTS company ( \
id INTEGER NOT NULL UNIQUE, \
name TEXT NOT NULL UNIQUE \
); \
CREATE TABLE IF NOT EXISTS availability ( \
year_season INTEGER NOT NULL UNIQUE, \
income_statement_get INTEGER NOT NULL, \
balance_sheet_get INTEGER NOT NULL \
);"
	
int DataRetrieve::OpenDatabase( const char* db_path )
{
	DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_DEBUG, "db_path: %s", db_path );

	int ret_code = 0;
	
	// flag to check if it's a new database
	bool is_new_database = false;
	
	do
	{
		// open database
		ret_code = sqlite3_open( db_path, &m_p_db );
		if( ret_code != SQLITE_OK )
		{
			DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_ERROR, "unable to open databse %s.", db_path );
			break;
		}
			
		// create tables
		char *zErrMsg = NULL;
			
		// create 
		ret_code = sqlite3_exec( m_p_db, CREATE_DATA_RETRIEVE_TABLES, NULL, NULL, &zErrMsg);
		if( ret_code != SQLITE_OK )
		{
			DEBUG_OUTPUT_WITH_FUNCTION_NAME( DEBUG_LEVEL_ERROR, "SQL error: %s", zErrMsg );
			sqlite3_free(zErrMsg);
			break;
		}
	} while( false );
	
	// check if databse need to close database due to fail
	if( ret_code ) CloseDatabase();
	
	return ret_code;
}

int DataRetrieve::CloseDatabase()
{
	if( m_p_db )
	{
		sqlite3_close( m_p_db );
		m_p_db = NULL;
	}
}

